<template>
  <div>
    <el-card>
      <el-form ref="form" :model="form" label-width="80px" size="mini">
        <el-form-item label="选择对象">
          <div style="display: flex; align-items: center">
            <div
              v-for="(item, index) in nowTreeArr"
              :key="item.id"
              class="myCheck"
              name="type"
              @click="deleteType(item, index)"
            >
              {{ item.name }}
              <i class="el-icon-circle-close" />
            </div>
          </div>
        </el-form-item>
        <div class="formtop">
          <el-form-item
            label="起始日期"
            label-width="auto"
            :rules="[{ required: true, message: '起始日期不能为空' }]"
            prop="start_time"
          >
            <el-date-picker
              v-model="form.start_time"
              value-format="yyyy-MM-dd"
              type="date"
              placeholder="选择日期"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item
            label-width="auto"
            :rules="[{ required: true, message: '截止日期不能为空' }]"
            prop="end_time"
          >
            <el-date-picker
              v-model="form.end_time"
              value-format="yyyy-MM-dd"
              type="date"
              placeholder="选择日期"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="search">查询</el-button>
          </el-form-item>
        </div>
      </el-form>

      <div :id="'energyRanking'" class="energyRanking_box" />
      <el-divider />
      <div :id="'energyRanking2'" class="energyRanking_box" />
      <el-divider />
      <el-button
        style="float: right; margin-bottom: 15px"
        type="primary"
        @click="exportExcel"
        >导出</el-button
      >

      <el-table :data="tableData" border style="width: 100%" class="table">
        <el-table-column prop="site_name" align="center" label="监测点" />
        <el-table-column prop="day" align="center" label="日期" />
        <el-table-column
          prop="column_value"
          align="center"
          label="最大需量（kW）"
        />
        <el-table-column prop="report_at" align="center" label="发生时间" />
      </el-table>
    </el-card>
  </div>
</template>
<script>
import * as echarts from 'echarts'
import commMix from './commonMix.js'
import { getDemandAnalysis } from '@/api/efficiencyAnalysisApi.js'
import * as XLSX from 'xlsx'
import FileSaver from 'file-saver'

export default {
  name: 'electricityComparisonChild',
  components: {},
  mixins: [commMix],
  props: {
    choseData: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {
      options: [],
      form: {
        monitor_id: [],
        site_id: [],
        start_time: '',
        end_time: '',
      },
      treeObj: [],
      value2: [],
      dropDownValue: '',
      optionsMetaAll: [],
      optionsMetaShow: [],
      valueMeta: [],
      input3: '',
      IndexGroup: [],
      nowTreeArr: [],
      optionArr: [],
      indexGroupParameterArr: [],
      chartArr: [],
      tableData: [],
      tableHead: [],
    }
  },
  watch: {
    choseData: {
      // 监听的对象
      deep: true, // 深度监听设置为 true
      handler: function (newV, oldV) {
        for (var i = 0; i < this.nowTreeArr.length; i++) {
          if (newV.id === this.nowTreeArr[i].id) {
            return
          }
          // 去重
        }
        this.nowTreeArr.push(newV)
        if (this.nowTreeArr.length === 1) {
          this.form.end_time = this.getDay(0)
          this.form.start_time = this.getDay(0)
          this.search()
        }
      },
    },
  },
  mounted() {},
  methods: {
    // 导出表格所用
    exportExcel() {
      if (this.tableData.length === 0) {
        this.$message({
          showClose: true,
          message: '暂无可用数据导出',
          type: 'error',
        })
        return
      }
      // 设置当前日期
      const time = new Date()
      const year = time.getFullYear()
      const month = time.getMonth() + 1
      const day = time.getDate()
      const name = year + '' + month + '' + day
      var wb = XLSX.utils.table_to_book(document.querySelector('.table'))
      var wbout = XLSX.write(wb, {
        bookType: 'xlsx',
        bookSST: true,
        type: 'array',
      })
      try {
        FileSaver.saveAs(
          new Blob([wbout], { type: 'application/octet-stream' }),
          name + '.xlsx'
        )
      } catch (e) {
        if (typeof console !== 'undefined') console.log(e, wbout)
      }
      return wbout
    },

    search() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          var monitorIdArr = []
          if (this.nowTreeArr.length === 0) {
            this.$message({
              showClose: true,
              message: '请选择监控设备',
              type: 'error',
            })
            return
          }
          for (var i = 0; i < this.nowTreeArr.length; i++) {
            monitorIdArr.push(this.nowTreeArr[i].id)
            this.form.site_id.push(this.nowTreeArr[i].site_id)
          }
          this.form.site_id = Array.from(new Set(this.form.site_id))
          this.form.monitor_id = monitorIdArr
          getDemandAnalysis(this.form).then((res) => {
            this.setEnergyRanking(res.data.line)
            this.setEnergyRanking2(res.data.circle)
            this.tableData = res.data.tableData
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    dropDownSearch() {
      var _this = this
      _this.valueMeta = []
      _this.optionsMetaShow = _this.optionsMetaAll.filter(_this.filterSearch)
    },
    filterSearch(item) {
      return item.includes(this.dropDownValue)
    },
    handleClick(tab, event) {
      console.log(tab, event)
    },
    setEnergyRanking(v) {
      echarts.dispose(document.getElementById('energyRanking'))
      var myChart = echarts.init(document.getElementById('energyRanking'))
      // 绘制图表
      var option = {
        xAxis: v.xAxis,
        yAxis: {
          type: 'value',
        },
        series: [v.series],
      }
      myChart.setOption(option)
      window.addEventListener('resize', () => {
        myChart.resize()
      })
    },
    setEnergyRanking2(v) {
      echarts.dispose(document.getElementById('energyRanking2'))
      var myChart = echarts.init(document.getElementById('energyRanking2'))
      // 绘制图表
      var option = {
        title: v.title,
        legend: {
          data: [v.legend.data],
        },
        radar: v.radar,
        series: [
          {
            ...v.series,
            areaStyle: {},
            tooltip: {
              trigger: 'item',
            },
          },
        ],
        tooltip: {
          position: ['55%', '0%'],
          formatter: function (params) {
            var datas = params.value
            var htms = "<div style='display:flex'>"
            // var a = 0
            for (var i = 1; i < datas.length + 1; i++) {
              if (i == 1) {
                htms +=
                  '<div style="width:48%;"><p>' +
                  i +
                  '点：' +
                  datas[i] +
                  '；</p>'
                // i = datas.length
              } else {
                if (i == 24) {
                  htms += '<p>' + i + '点：' + datas[0] + '；</p>'
                } else {
                  htms += '<p>' + i + '点：' + datas[i] + '；</p>'
                }

                if (i - 1 == 11) {
                  htms += "</div><div style='width:48%;margin-left:4%'>"
                } else if (i - 24 == 0) {
                  htms += '</div>'
                  break
                }
              }
              // ss++
            }
            htms += '</div>'
            return htms
          },
        },
      }
      myChart.setOption(option)
      window.addEventListener('resize', () => {
        myChart.resize()
      })
    },
  },
}
</script>

<style lang='scss' scoped>
::v-deep .tableHead {
  background-color: #edf1f8 !important;
}

.formtop {
  display: flex;
  align-items: center;
  justify-content: flex-start;
}

.min_box {
  width: 100%;
  height: 70vh;

  .el-card {
    & > div {
      width: 100%;
      height: 40vh;
    }
  }
}

#energyRanking,
.energyRanking_box {
  width: 100%;
  height: 40vh;
}

.bottom_box {
  width: 100%;
  height: 50%;
  display: flex;
  align-items: center;
  justify-content: space-between;

  & > div {
    width: 45%;
    height: 34vh;
  }
}

::v-deep .is-required {
  display: flex;
  align-items: center;
  margin-left: 20px;
}

.myCheck {
  padding: 0 30px 0 20px;
  border: 1px solid #c6c6c6;
  border-radius: 10px;
  margin-left: 10px;
  display: flex;
  align-items: center;
  position: relative;
  cursor: pointer;

  i {
    color: #c6c6c6;
    font-size: 25px;
    position: absolute;
    right: 0;
    top: 50%;
    transform: translateY(-50%);
  }
}
</style>
